<html>
<head>
	<title>CS143 Project 1B Query</title>
	<style type="text/css">
	table, tr, td, th
	{
		border: 1px solid black;
		border-collapse: collapse;
		padding: 10px;
		text-align: center;
	}

	</style>
</head>
<body>
<p>Type an SQL query in the following box:</p>
<p>
	<form action="query.php" method="GET">
	<textarea name="query" cols="60" rows="8"><?php echo $_GET["query"]; ?></textarea><br/>
	<input type="submit" value="Submit" />
	</form>
</p>

<?php 
$query = $_GET["query"];
if ($query)
{
	$pattern="/^(select)/i";
	if(preg_match($pattern, $query))
	{
		$db_connection = mysql_connect("localhost", "cs143", "");
		if(!$db_connection)
		{
			$errmsg = mysql_error($db_connection);
			print "Connection failed: $errmsg <br />";
			exit(1);
		}
		else
		{
			mysql_select_db("CS143", $db_connection);
			$rs = mysql_query($query, $db_connection);
			echo "<table>";
			$i = 0;
			while($row = mysql_fetch_row($rs)) 
			{
				if ($i == 0)
				{
					$num_cols = count($row);
					echo "<tr>";
					for(; $i < $num_cols; $i++)
					{
						$field_name = mysql_field_name($rs, $i);
						echo "<th>" . $field_name ."</th>";
					}
					echo "</tr>";
				}
				echo "<tr>";
				foreach ($row as $x)
				{
					if (is_null($x))
						echo "<td>N/A</td>";
					else
						echo "<td>" . $x . "</td>";
				}
				echo "</tr>";
			}	
			echo "</table>";
			mysql_close($db_connection);
		}
	}
	else
	{
		echo "Please enter a SELECT query.";
	}
}
?>
</body>
</html>
